import { createElement, renderBackgroundMenus, renderExampleMenus, renderDocumentMenus } from './dom'

let tab, right, menus, tabHash

const codeDom = document.createElement('div')
codeDom.className = 'code-p'

function init() {
  document.body.innerHTML = ''
  const root = createElement('div', document.body, 'root')
  const left = createElement('div', root, 'left')
  right = createElement('div', root, 'right')
  const logo = createElement('div', left, 'logo')
  const name = createElement('span', logo, 'name')
  name.innerText = 'GraphBack'
  tab = createElement('span', logo, 'tab')
  addTab('文档', 'document', tab)
  addTab('示例', 'example', tab)
  addTab('背景', 'background', tab)
  // menus
  menus = createElement('div', left, 'menus')
}

function addTab(name: string, router: string, parent: HTMLElement) {
  let span = createElement('span', parent)
  span.dataset.router = router
  span.innerText = name
  span.onclick = () => changeTab(router)
}

function changeTab(router: string) {
  activeTab(router)
  location.hash = '/' + router
}

function activeTab(router: string) {
  tab.parentElement?.querySelectorAll('span').forEach((item: HTMLElement) => {
    if (item.dataset.router == router) item.classList.add('active')
    else item.classList.remove('active')
  })
  if (tabHash == router) return
  if (router == 'example') renderExampleMenus()
  else if (router == 'background') renderBackgroundMenus()
  else if (router == 'document') renderDocumentMenus()
  tabHash = router
}

function changeMenu(menu: string) {
  location.hash = '/' + tabHash + '/' + menu
}

function activeMenu(menu) {
  for (let i = 0; i < menus.children.length; i++) {
    let item = menus.children[i]
    if (item.innerText == menu) item.classList.add('active')
    else item.classList.remove('active')
  }
}

export { right, menus, codeDom, activeTab, changeTab, changeMenu, activeMenu, init }
